package cn.iocoder.yudao.module.system.service.userChangeMobileRecordrecord;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.framework.tenant.core.aop.TenantIgnore;
import cn.iocoder.yudao.module.member.api.company.CompanyApi;
import cn.iocoder.yudao.module.member.api.company.dto.CompanyRespDTO;
import cn.iocoder.yudao.module.member.api.company.dto.CompanyUpdateReqDTO;
import cn.iocoder.yudao.module.system.api.message.MessageApi;
import cn.iocoder.yudao.module.system.api.message.dto.MessageCreateReqDTO;
import cn.iocoder.yudao.module.system.api.tenant.TenantUserApi;
import cn.iocoder.yudao.module.system.api.tenant.dto.TenantRepVo;
import cn.iocoder.yudao.module.system.api.tenant.dto.TenantUpadateVo;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.controller.admin.userChangeMobileRecordrecord.vo.UserChangeMobileRecordrecordCreateReqVO;
import cn.iocoder.yudao.module.system.controller.admin.userChangeMobileRecordrecord.vo.UserChangeMobileRecordrecordExportReqVO;
import cn.iocoder.yudao.module.system.controller.admin.userChangeMobileRecordrecord.vo.UserChangeMobileRecordrecordPageReqVO;
import cn.iocoder.yudao.module.system.controller.admin.userChangeMobileRecordrecord.vo.UserChangeMobileRecordrecordUpdateReqVO;
import cn.iocoder.yudao.module.system.convert.userChangeMobileRecordrecord.UserChangeMobileRecordrecordConvert;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.dataobject.userChangeMobileRecordrecord.UserChangeMobileRecordrecordDO;
import cn.iocoder.yudao.module.system.dal.mysql.userChangeMobileRecordrecord.UserChangeMobileRecordrecordMapper;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.USER_CHANGE_MOBILE_RECORDRECORD_NOT_EXISTS;

/**
 * 用户手机更新记录 Service 实现类
 *
 * @author 谭万全
 */
@Service
@Validated
public class UserChangeMobileRecordrecordServiceImpl implements UserChangeMobileRecordrecordService {

    @Resource
    private UserChangeMobileRecordrecordMapper userChangeMobileRecordrecordMapper;
    @Autowired
    private AdminUserApi adminUserApi;
    @Resource
    private TenantUserApi tenantUserApi;
    @Autowired
    @SuppressWarnings("SpringJavaAutowiredFieldsWarningInspection") // UserService 存在重名
    private AdminUserService adminUserService;
    @Resource
    private CompanyApi companyApi;
    @Resource
    private MessageApi messageApi;
    @Override
    public Long createUserChangeMobileRecordrecord(UserChangeMobileRecordrecordCreateReqVO createReqVO) {
        // 插入
        UserChangeMobileRecordrecordDO userChangeMobileRecordrecord = UserChangeMobileRecordrecordConvert.INSTANCE.convert(createReqVO);
        userChangeMobileRecordrecordMapper.insert(userChangeMobileRecordrecord);
        // 返回
        return userChangeMobileRecordrecord.getId();
    }

    @Override
    public void updateUserChangeMobileRecordrecord(UserChangeMobileRecordrecordUpdateReqVO updateReqVO) {
        // 校验存在
        this.validateUserChangeMobileRecordrecordExists(updateReqVO.getId());
        // 更新
        UserChangeMobileRecordrecordDO updateObj = UserChangeMobileRecordrecordConvert.INSTANCE.convert(updateReqVO);
        userChangeMobileRecordrecordMapper.updateById(updateObj);
    }

    @Override
    public void deleteUserChangeMobileRecordrecord(Long id) {
        // 校验存在
        this.validateUserChangeMobileRecordrecordExists(id);
        // 删除
        userChangeMobileRecordrecordMapper.deleteById(id);
    }

    private void validateUserChangeMobileRecordrecordExists(Long id) {
        if (userChangeMobileRecordrecordMapper.selectById(id) == null) {
            throw exception(USER_CHANGE_MOBILE_RECORDRECORD_NOT_EXISTS);
        }
    }

    @Override
    public UserChangeMobileRecordrecordDO getUserChangeMobileRecordrecord(Long id) {
        return userChangeMobileRecordrecordMapper.selectById(id);
    }

    @Override
    public List<UserChangeMobileRecordrecordDO> getUserChangeMobileRecordrecordList(Collection<Long> ids) {
        return userChangeMobileRecordrecordMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<UserChangeMobileRecordrecordDO> getUserChangeMobileRecordrecordPage(UserChangeMobileRecordrecordPageReqVO pageReqVO) {
        return userChangeMobileRecordrecordMapper.selectPage(pageReqVO);
    }

    @Override
    public List<UserChangeMobileRecordrecordDO> getUserChangeMobileRecordrecordList(UserChangeMobileRecordrecordExportReqVO exportReqVO) {
        return userChangeMobileRecordrecordMapper.selectList(exportReqVO);
    }

    @Override
    public void authenticationUserPhone(Long id,int status,String remark) {
        AdminUserDO adminUserRespDTO= adminUserService.getUser(SecurityFrameworkUtils.getLoginUserId());
        // 校验存在
        UserChangeMobileRecordrecordDO updateObj = userChangeMobileRecordrecordMapper.selectById(id);
        if(updateObj==null){
            throw exception(USER_CHANGE_MOBILE_RECORDRECORD_NOT_EXISTS);
        }
        //修改更换手机号记录
        updateObj.setUpdater(adminUserRespDTO.getUsername());
        updateObj.setStatus(status);
        updateObj.setRemark(remark);
        updateObj.setCheckTime(new Date());
        userChangeMobileRecordrecordMapper.updateById(updateObj);
        //查询企业
        CompanyRespDTO companyRespDTO=companyApi.getCompanyById(updateObj.getCompanyId());
        CompanyUpdateReqDTO companyUpdateReqDTO=new CompanyUpdateReqDTO();
        BeanUtils.copyProperties(companyRespDTO,companyUpdateReqDTO);
        String title;
        String message;
        //更新用户手机
        if(status==1) {
            //更新用户手机
            adminUserApi.updateUsersPhone(updateObj.getUserId(), updateObj.getNewMobile(),0);
            //更新租户手机
            TenantRepVo tenantRepVo=tenantUserApi.getTenantByMobile(updateObj.getUsername());
            TenantUpadateVo tenantUpadateVo=new TenantUpadateVo();
            tenantUpadateVo.setContactMobile(updateObj.getNewMobile());
            tenantUpadateVo.setId(tenantRepVo.getId());
            tenantUserApi.updateTenantMobile(tenantUpadateVo);
            //更新用户企业
            companyUpdateReqDTO.setPhoneNumber(updateObj.getNewMobile());
            companyUpdateReqDTO.setAuthorizedStatus("authorized");
            if(StringUtils.isNotBlank(updateObj.getApplyUserName())){
                companyUpdateReqDTO.setApplyUserName(updateObj.getApplyUserName());
            }
            if(StringUtils.isNotBlank(updateObj.getCardNo())){
                companyUpdateReqDTO.setCardNo(updateObj.getCardNo());
            }
            if(StringUtils.isNotBlank(updateObj.getAuthenticationFrontPictureUrl())){
                companyUpdateReqDTO.setAuthenticationFrontPictureUrl(updateObj.getAuthenticationFrontPictureUrl());
            }
            if(StringUtils.isNotBlank(updateObj.getAuthenticationBackPictureUrl())){
                companyUpdateReqDTO.setAuthenticationBackPictureUrl(updateObj.getAuthenticationBackPictureUrl());
            }
            companyApi.updateCompany(companyUpdateReqDTO);
            title=companyUpdateReqDTO.getCompanyName()+"-"+updateObj.getNickname()+"：企业身份认证审核通过";
            message="您好，"+companyUpdateReqDTO.getCompanyName()+"的更换手机号审核已通过，提交人："+updateObj.getNickname()+"；审核人："+adminUserRespDTO.getNickname() ;
            sendmessage(1l,updateObj.getUserId(),title,message);
            //发送给运营
            title=companyUpdateReqDTO.getCompanyName()+"-"+updateObj.getNickname()+"：企业更换手机号审核-审核通过";
            List<Long> ids= adminUserApi.getUserIdsByTenant(2l);
            for (Long id1:ids) {
                sendmessage(1l,id1,title,message);
            }
        }else{
            companyUpdateReqDTO.setAuthorizedStatus("authorized");
            companyApi.updateCompany(companyUpdateReqDTO);
            title=companyUpdateReqDTO.getCompanyName()+"-"+updateObj.getNickname()+"：企业身份认证审核失败";
            message="您好，"+companyUpdateReqDTO.getCompanyName()+"的更换手机号审核失败，失败原因"+remark+" 提交人："+updateObj.getNickname()+"；审核人："+adminUserRespDTO.getNickname() ;
            sendmessage(1l,updateObj.getUserId(),title,message);
            //发送给运营
            title=companyUpdateReqDTO.getCompanyName()+"-"+updateObj.getNickname()+"：企业更换手机号审核-审核失败";
            List<Long> ids= adminUserApi.getUserIdsByTenant(2l);
            for (Long id1:ids) {
                sendmessage(1l,id1,title,message);
            }
        }



    }

    @Override
    @TenantIgnore
    public UserChangeMobileRecordrecordDO getUserChangeMobileRecordrecordByPhone(String phone) {
        return userChangeMobileRecordrecordMapper.selectOne("new_mobile",phone,"status",0);
    }

    @Async
    void sendmessage(Long type, Long id, String title, String messageText){
        MessageCreateReqDTO messageCreateReqVO=new MessageCreateReqDTO();
        messageCreateReqVO.setPhone("");
        messageCreateReqVO.setType(type);
        messageCreateReqVO.setStatus("5");
        messageCreateReqVO.setUserId(id);
        messageCreateReqVO.setStudentName("系统管理员");
        messageCreateReqVO.setRemark(messageText);
        messageCreateReqVO.setTitle(title);
        messageApi.sendMessage(messageCreateReqVO);
    }
}
